package com.zl.org.service.impl;


import com.zl.basic.service.impl.BaseServiceImpl;
import com.zl.org.domain.Department;
import com.zl.org.mapper.DepartmentMapper;
import com.zl.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void save(Department department) {
        departmentMapper.save(department);
        String dirPath="";
        if (department.getParent_id()==null){
            Long id = department.getId();
            dirPath="/"+id;
        }else {
            Long departmentId = department.getParent_id();
            Department department1 = departmentMapper.loadById(departmentId);
            dirPath = department1.getDirPath()+"/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);

    }
    @Transactional
    @Override
    public void update(Department department) {
        String dirPath="";
        if (department.getParent_id()==null){
            Long id = department.getId();
            dirPath="/"+id;
        }else {
            Long departmentId = department.getParent_id();
            Department department1 = departmentMapper.loadById(departmentId);
            dirPath = department1.getDirPath()+"/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);


    }
    @Override
    public List<Department> deptTree() {
        List<Department> all = departmentMapper.loadAll();
        Map<Long,Department> map  = new HashMap<>();
        for (Department department : all) {
            map.put(department.getId(),department);
        }

        List<Department> deptTree = new ArrayList<>();
        for (Department department:all){
            if(department.getParent_id() == null){
                deptTree.add(department);
            }else{
                Long parent_id = department.getParent_id();
                Department parentDepartment = map.get(parent_id);
                parentDepartment.getChildren().add(department);
            }
        }
        return deptTree;
    }
}
